package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    @Override
    public ResponseResult listByName(ChannelDto dto) {
        //1. 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 条件分页查询
        LambdaQueryWrapper<WmChannel> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotBlank(dto.getName()), WmChannel::getName, dto.getName());
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        this.page(page, qw);
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    // 新增频道
    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {

        if (StringUtils.isBlank(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //        频道名称不能重复
        //        新增之前应该根据名称查询
        //        如果能查出结果 返回数据已存在
        //        如果没有查出结果再新增
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName, wmChannel.getName());
        WmChannel one = this.getOne(queryWrapper);
        if (one != null) {  // 如果能查出结果 返回数据已存在
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        } else {
            wmChannel.setCreatedTime(new Date());
            this.save(wmChannel);
        }
        return ResponseResult.okResult();
    }
}
